import Loading from '@/components/Loading';
import { api } from '@/utils/request/Api';
import { Ionicons } from '@expo/vector-icons';
import { router, useLocalSearchParams } from 'expo-router';
import { Email,Temlpate } from '@/interface/interface';
import React, { useEffect, useState } from 'react';
import Toast from '@/components/Toast';
import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import Clipboard from '@react-native-clipboard/clipboard';
export default function EmailsScreen() {
  const { crawlId } = useLocalSearchParams<{ crawlId: string }>();
  const [emails, setEmails] = useState<Email[]>([]);
  const [count, setCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const [copiedText, setCopiedText] = useState('');
  const [showToast,setShowToast] = useState(false);
  useEffect(() => {
    setLoading(true)
    api.get("email/list",{params:{crawl_id:crawlId,status:0}}).then((res) => {
      setLoading(false);
      if(res && res.code == 1){
        setEmails(res.data.data);
        setCount(res.data.total);
      }
      
    })
  }, [crawlId]);
  /**
   * 刪除
   */
  const onDelete = (id:number) => {
    setLoading(true)
    api.get("email/delete",{params:{id:id}}).then((res) => {
      setLoading(false);
      
      if(res && res.code == 1){
        setCount(count-1)
        setEmails(emails.filter((item) => item.id !== id));
      }
      
    })
  }
  const copyEmail = (email:string) => {
     console.log(email,100000)
     Clipboard.setString(email);
     setShowToast(true)
     setTimeout(() => {setShowToast(false)},1000)
  }
  /**保存確認郵件 */
  const onSave = () => {
      setLoading(true)
      api.get("email/save",{params:{crawl_id:crawlId}}).then((res) => {
        setLoading(false);
        router.push(`/campaigns?crawlId=${crawlId}`);
      })
  }
  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>Saved Emails</Text>
        <TouchableOpacity>
          <Ionicons name="trash-outline" size={22}  color="#f43f5e" />
        </TouchableOpacity>
      </View>

      <View style={styles.subHeader}>
        <Text style={styles.found}>{count} Emails Found</Text>
        <TouchableOpacity style={styles.saveBtn}>
          <Text style={styles.saveText} onPress={() => onSave()}>Save All</Text>
        </TouchableOpacity>
      </View>

      <View style={styles.groupBox}>
        <View style={styles.groupHeader}>
          <Ionicons name="globe-outline" size={16} color="#333" style={{ marginRight: 4 }} />
          <Text style={{ fontWeight: '600' }}>Main Page</Text>
          <Text style={{ marginLeft: 'auto', color: '#666' }}>{count} emails</Text>
        </View>

        <FlatList
          data={emails}
          keyExtractor={(item:any) => item?.id??0}
          renderItem={({ item:Email }) => (
            <View style={styles.emailRow}>
              <Ionicons name="person-circle-outline" size={18} color="#888" />
              <Text style={styles.emailText}>{Email?.email??''}</Text>
              <Ionicons name="copy-outline" onPress={()=>copyEmail(Email.email)} size={18} color="#999" style={{ marginLeft: 'auto', marginRight: 10 }} />
              <Ionicons name="trash" onPress={() => onDelete(Email?.id??0)} size={18} color="#f43f5e" />
            </View>
          )}
        />
      </View>
      {loading && <Loading />}
      <Toast message='復製成功' visible={showToast}></Toast>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, padding: 20, backgroundColor: '#fff' },
  header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' },
  title: { fontSize: 22, fontWeight: '600' },
  subHeader: {
    flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 12
  },
  found: { fontWeight: '500', fontSize: 14 },
  saveBtn: {
    backgroundColor: '#f472b6', paddingHorizontal: 16, paddingVertical: 6,
    borderRadius: 20
  },
  saveText: { color: '#fff', fontWeight: '600' },
  groupBox: {
    marginTop: 20, backgroundColor: '#f9fafb', padding: 16, borderRadius: 12
  },
  groupHeader: {
    flexDirection: 'row', alignItems: 'center', marginBottom: 10
  },
  emailRow: {
    flexDirection: 'row', alignItems: 'center', paddingVertical: 8, borderBottomWidth: 1,
    borderColor: '#eee'
  },
  emailText: { marginLeft: 10, fontSize: 14, color: '#333' }
  
});
